package com.ly.spring.mvc.web;

import com.ly.spring.mvc.entity.Result;
import com.ly.spring.mvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

// Controller 默认当前对象所有方法返回的是视图名
// RestController 默认.....是json数据

@Controller
public class IndexController {

    @GetMapping("toTest")
    public String toTest(String name, HttpServletRequest request){
        System.out.println("==========toTest==========");
        request.setAttribute("myname", name);
        User user = new User();
        user.setName(name);
        request.getSession().setAttribute("myinfo", user);
        return "test.jsp";
    }

    @GetMapping("myinfo")
    @ResponseBody
    public User myinfo(@SessionAttribute User myinfo){
        return myinfo;
    }

    @RequestMapping("reg")
    @ResponseBody
    public Result reg(@Valid User user, Errors errors){
        if (errors.hasErrors()) {
            return new Result(0, "验证错误!",
                    errors.getAllErrors());
        } else {
            System.out.println("user = " + user);
            int i= 1/0;
            return new Result(1, "注册成功!",
                    null);
        }
    }

    @PostMapping("upload")
    @ResponseBody
    public Result uploadHead(@RequestParam("head") MultipartFile file,
                             User user) throws IOException {
        // 获取上传的文件名
        String filename = file.getOriginalFilename();
        file.transferTo(new File("F:\\上课视频\\143\\1116\\" + filename));
        return new Result(1,"文件上传成功", user);
    }


}
